#include "file_op.h"
#include "fs.h"
#include "sync.h"
#include <stdio.h>
#include <string.h>

// 路径合法性检查
static int valid_path(const char *path) {
    if (path == NULL || path[0] != '/') {
        printf("错误：路径必须以 / 开头（非法路径：%s）\n", path ? path : "NULL");
        return 0;
    }
    return 1;
}

void wait_for_enter() {
    int c;
    printf("Press Enter to continue...\n");
    while ((c = getchar()) != '\n' && c != EOF); // 清除缓冲区
}

// 目录操作
int my_mkdir(const char *path) {
    if (!valid_path(path)) return -1;
    return fs_create_dir(path);
}

int my_rmdir(const char *path) {
    if (!valid_path(path)) return -1;
    return fs_delete(path);  // 目录必须为空
}

int my_rm(const char *path) {
    if (!valid_path(path)) return -1;
    return fs_delete(path);  // 文件或空目录
}

int my_ls(const char *path) {
    if (!valid_path(path)) return -1;
    return fs_list_dir(path);
}

int my_rename(const char *old_path, const char *new_path) {
    if (!valid_path(old_path) || !valid_path(new_path)) return -1;
    return fs_rename(old_path, new_path);
}

// 文件操作

int my_create(const char *path) {
    if (!valid_path(path)) return -1;
    return fs_create_file(path);
}

int my_write(const char *path, const void *buf, size_t len) {
    if (!valid_path(path)) return -1;
    
    int id = path_lookup(path);
    if (id < 0) {
        printf("错误：路径不存在：%s\n", path);
        return -1;
    }

    lock_acquire_write(id);
    int n = fs_write_file(path, buf, len);
    wait_for_enter();
    lock_release_write(id);

    return n;
}

int my_read(const char *path, void *buf, size_t len) {
    if (!valid_path(path)) return -1;
    
    int id = path_lookup(path);
    if (id < 0) {
        printf("错误：路径不存在：%s\n", path);
        return -1;
    }

    lock_acquire_read(id);
    int n = fs_read_file(path, buf, len);
    wait_for_enter();
    lock_release_read(id);
    
    return n;
}

int my_stat(const char *path) {
    if (!valid_path(path)) return -1;

    FileInfo info;
    if (fs_stat(path, &info) == 0) {
        printf("inode: %d, 类型: %s, 大小: %zu 字节\n",
               info.inode_id,
               info.type == 1 ? "目录" : "文件",
               info.size);
        return 0;
    } else {
        printf("错误：无法获取路径信息：%s\n", path);
        return -1;
    }
}
